/**
 * ConfigLoader.java
 *
 * Copyright (C) 2009,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package ws4is.engine;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import ws4is.engine.enums.ActionScope;
import ws4is.engine.enums.HTTPRequestType;
import ws4is.engine.utils.JsonUtil;
import ws4is.engine.utils.ResourceFinder;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

/*
 * Class for configuration initialization and request processing 
 */
public class ConfigLoader {

	private transient String param_action = null;
	private Type mapType = null;
	private Map<String, ConfigObject> services = null;
	private ServletContext context;
	private IDispatcher dispatcher;

	public ConfigLoader(ServletContext ctx, IDispatcher dpch)throws ServletException  {
		context = ctx;
		dispatcher = dpch;
		mapType = new TypeToken<Map<String, ConfigObject>>() {}.getType();
		services = new HashMap<String, ConfigObject>();
		init();
		for (Entry<String,ConfigObject> e : services.entrySet()){
			if (dpch.getClass().isAssignableFrom(ADispatcherServlet.class)){
				e.getValue().setDefaultScope(ActionScope.SESSION);	
			} else if (dpch.getClass().isAssignableFrom(ADispatcherFilter.class)){
				e.getValue().setDefaultScope(ActionScope.GLOBAL);	
			}			
		}

	}

	public void init() throws ServletException {
		try {
			load(dispatcher.getClass());
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

	// load file from META-INF/actions/ named as abstract class/interface
	// canonical name
	// each line should contain canonical class names implementing
	// interface or abstract class
	private final void load(Class<? extends IDispatcher> ifc) throws Exception {
		String vpath = "META-INF/actions/" + ifc.getName() + ".json";
		Map<String, ConfigObject> daat = load(vpath,mapType);
		getClasses(daat);
		services.putAll(daat);
		
	}
	
	
	public final HashMap load(String vpath, Type mapType ) throws Exception {

		String s = context.getRealPath(vpath);
		ResourceFinder re = new ResourceFinder(s);

		HashMap daat = null;
		
		InputStream is = re.getInputStream();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			StringBuffer sb = new StringBuffer();
			String eachLine = br.readLine();

			while (eachLine != null) {
				sb.append(eachLine);
				eachLine = br.readLine();
			}

			Gson gs = new Gson();
			daat = gs.fromJson(sb.toString(), mapType);			
			gs = null;
			
		}catch(Exception e){
			//TODO log error reading web.xml configuration
			throw e;
		} finally {
			is.close();			
		}
		return daat;
	}

	private final void getClasses(Map<String, ConfigObject> daat) {

		Set<Entry<String, ConfigObject>> set = daat.entrySet();
		for(Entry<String, ConfigObject> e : set){
			e.getValue().setActionClass();
		}

	}

	 private static String stack2string(Exception e) {
		  try {
		    StringWriter sw = new StringWriter();
		    PrintWriter pw = new PrintWriter(sw);
		    e.printStackTrace(pw);		    
		    return JsonUtil.stringToHTMLString(sw.toString());
		  }
		  catch(Exception e2) {
		    return "";
		  }
	}
	
	private String getAction(HTTPRequestType type,	HttpServletRequest request, HttpServletResponse response) {

		param_action = dispatcher.preAction(type, request);

		if(param_action==null) return null;
		
		String actionClass = null;
		if ((type == HTTPRequestType.GET) ||(type == HTTPRequestType.FILTER)) {
			actionClass = request.getParameter(param_action);
		} else {
			
			if (ServletFileUpload.isMultipartContent(request)) {
				
				Cookie[] cookies = request.getCookies();
				for (Cookie cookie : cookies){
					if(param_action.equals(cookie.getName()))
						actionClass =  cookie.getValue();	
				}
								
				type = HTTPRequestType.MULTIPART;
				
			} else {
				Map pmap = request.getParameterMap();
				if (pmap.containsKey(param_action)) {
					actionClass = request.getParameter(param_action);
				}
			}
		}
		
		return actionClass;
	}
	
	
	
	// from URL request parameter [action] retrieves action class name,
	// instantiate it and execute method from parameter [cmd]
	// Example :
	// http://localhost:8080/myapp/myservlet/action=EditorAction&cmd=loadLanguages
	// will instantiate EditorAction class (subclass of ServletAction) and call
	// loadLanguages method
	// loadLanguages method must have HttpServletRequest and HttpServletResponse
	// as input parameters. If method is part of Filter action it must return boolean values where true means chain.dofilter else response json false.
	// If method is part of the servlet action it has void; nothing to return
	public final void processAction(HTTPRequestType type,	HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
		processAction(type,request,response,null);
	}
	
	public final void processAction(HTTPRequestType type,	HttpServletRequest request, HttpServletResponse response,FilterChain chain) throws Exception, IOException {
		String actionClass = getAction(type,request,response);
		dispatcher.callMethod(actionClass,services.get(actionClass),type,request,response,chain);
	}


	/*
	 * Prints error message in jSON format
	 */	
	 public final void printMessage(HttpServletResponse response, String msg) throws UnsupportedEncodingException, IOException{
		printMessage(response,null,msg);
	}
	
	public final void printMessage(HttpServletResponse response, Exception e, String msg) throws UnsupportedEncodingException, IOException{
		
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
		JsonObject jobj = new JsonObject();
		jobj.addProperty("success", new Boolean(false));
		
		if(e!=null){
			jobj.addProperty("msg", e.getMessage());
			jobj.addProperty("msgDetailed", stack2string(e));
		}else
			jobj.addProperty("msg", msg);	
		
		Gson gs = new Gson();
		pw.write(gs.toJson(jobj));
		pw.flush();
		pw.close();
		jobj=null;
		gs=null;
	}

	public void releaseResources(){
		Set<Entry<String,ConfigObject>> set = services.entrySet();
		for(Entry<String,ConfigObject> e : set){
			e.getValue().releaseResources();
		}
		services.clear();
		services=null;;
		param_action = null;
		mapType = null;
		context=null;
		dispatcher=null;
	}



}
